
from datetime import datetime
import os
import secrets
import time
from moviepy.editor import *
import requests
import oss2
import uuid
from logger import v_logger
from utils.asr import only_asr


OSS_AccessKeyId = "LTAI5tFjf9gT3yfBYf6cWRnX"
OSS_AccessKeySecret = "PXYCrvmt3ROJXyX69y9O4gWGi6AtDG"
OSS_EndPoint = "oss-cn-hangzhou.aliyuncs.com"
OSS_BucketNam = "wenan-hz"
OSS_prefix = 'https://cdn.hz.tcbot.cc/'


def upload_file(path, type=".mp4"):
    base64_url_prefix = None
    try:
        print("开始上传")
     # 上传oss
        auth = oss2.Auth(OSS_AccessKeyId,
                         OSS_AccessKeySecret)
        # Endpoint以杭州为例，其它Region请按实际情况填写。
        bucket = oss2.Bucket(
            auth, OSS_EndPoint, OSS_BucketNam)
        current_date = datetime.now().strftime("%Y%m%d")
        OssPrefix = f"xcx_task/{current_date}/"
        file_name = OssPrefix + str(uuid.uuid1())+type
        # 上传视频
        bucket.put_object_from_file(file_name, path)

        base64_url_prefix = OSS_prefix + file_name
        # logger.error('Failed to download image from URL: %s', image_url)
    except Exception as e:
        print(e)
        return None
        # logger.exception('An error occurred during image processing: %s', e)
    return base64_url_prefix


def generate_cookie():
    # Generate parts of the cookie with appropriate random or static values
    __ac_nonce = secrets.token_hex(8)  # Similar length as your example
    # Starting with _02 followed by random
    __ac_signature = '_02' + secrets.token_hex(25)
    # Random token, adjusting length to match
    ttwid = f"1|{secrets.token_urlsafe(44)}"
    # Based on current time + random
    tt_webid = str(int(time.time())) + secrets.token_hex(5)
    msToken = secrets.token_urlsafe(50)  # Random token, length adjusted
    ttcid = secrets.token_hex(16)  # Random 32 character string
    tt_scid = secrets.token_hex(20)  # Random 40 character string
    # Prefix with 'verify_' + random
    s_v_web_id = 'verify_' + secrets.token_hex(20)

    # Concatenate all parts to form the full cookie string
    cookie_parts = [
        f'__ac_nonce={__ac_nonce}',
        f'__ac_signature={__ac_signature}',
        f'ttwid={ttwid}',
        f'tt_webid={tt_webid}',
        f'msToken={msToken}',
        f'ttcid={ttcid}',
        f'tt_scid={tt_scid}',
        f's_v_web_id={s_v_web_id}',
    ]
    out = '; '.join(cookie_parts)
    return out


cookies = generate_cookie()
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
    'Cookie': cookies
}


def is_path(name=None):
    folder_path = name
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)


def video2audio(file_name, out_name):
    current_date = datetime.now().strftime("%Y%m%d")
    path = f"{out_name}.mp3"
    prefix = f"out/{current_date}/"
    out_file_name = prefix + path
    is_path(prefix)
    try:
        video = VideoFileClip(file_name)  # 读取视频文件
        v_logger.info(f"视频时长：{video.duration}s")
        v_logger.info(f"视频大小：{video.size[0]}x{video.size[1]}")
        if video.duration > 15*60:
            return None
        # 设置压缩参数
        # video = video.fx(vfx.resize, width=1280)  # 可以调整视频分辨率
        # clip = video.set_fps(10)  # 可以调整帧率

        # 压缩视频
        # is_path("out")
        # clip.write_videofile("out/tmp.mp4", codec="libx264", bitrate="700k")

        # speedVideo = video.speedx(2)  # 设置视频倍速播放
        audioclip1 = video.audio  # 从视频对象中提取音频
        # audioclip1.write_audiofile(out_file_name)  # 写入音频文件
        # 写入音频文件，指定比特率和采样率
        audioclip1.write_audiofile(
            out_file_name,
            codec='libmp3lame',  # 使用 MP3 编码
            bitrate='320k',  # 设置比特率为 320 kbps
            ffmpeg_params=['-ar', '44100']  # 设置采样率为 44.1 kHz
        )

        # # 截取视频的第5秒作为截图
        # frame = video.get_frame(5)  # 获取第5秒的视频帧

        # # 保存截图
        # frame_image = ImageClip(frame)  # 将帧转换为 ImageClip 对象
        # frame_image.save_frame("screenshot.png")  # 保存为图片文件

        # 关闭资源
        audioclip1.close()  # 关闭音频剪辑
        video.close()  # 关闭视频剪辑

        # # 提取前10秒的音频
        # audioclip10s = video.audio.subclip(0, 10)
        # # 写入音频文件
        # audioclip10s.write_audiofile('out/test4.mp3')
    except Exception as e:
        return None
        # logger.exception('An error occurred during image processing: %s', e)
    return file_name


def download_video(url, out_name, type='mp4'):
    file_name = f"input/{out_name}.{type}"
    is_path("input")
    try:
        response = requests.get(url, headers=headers, timeout=60*5)
        if response.status_code == 200:
            v_logger.info(f"数据大小: {len(response.content)}")
            with open(file_name, "wb") as f:
                f.write(response.content)
        else:
            return None
    except Exception as e:
        return None
    return file_name


def main(url, type="mp4"):
    start_time = time.time()
    local_name = download_video(url, 'tmp', type)
    if local_name is None:
        v_logger.info(f"下载视频报错")
        return None
    audio_file_name = local_name
    if type == "mp4":
        audio_file_name = video2audio(local_name, "tmp")
    if audio_file_name is None:
        v_logger.info(f"提取音频错误")
        return None
    text, _ = only_asr(audio_file_name)
    end_time = time.time()

    execution_time = end_time - start_time  # 计算执行时间
    v_logger.info(f"函数执行时间为: {execution_time} 秒")
    return text


def compress_video(input_path, target_bitrate='2M'):
    current_date = datetime.now().strftime("%Y%m%d")
    path_local_audio = f"out/{current_date}/tmp1.mp3"
    path_local_video = f"out/{current_date}/tmp1.mp4"
    video = VideoFileClip(input_path)

    # 在进行视频压缩时，你可以选择保留音频或移除音频。如果你打算保留音频，请确保视频文件中包含音频轨道。如果你想删除音频，请使用without_audio()方法。
    if video.audio is not None:
        audio_clip = video.audio

        # 定义分离的音频文件路径为 后缀变成mp3的output_path
        # 这里其实用os模块来定义路径最好
        audio_clip.write_audiofile(path_local_audio, codec='mp3')
        audio_clip.close()
        # 删除音频轨道
        video = video.without_audio()
        path_audio = upload_file(path_local_audio, ".mp3")
    # compressed_video = video.resize(width=1280)  # 调整视频分辨率（可选）
    video.write_videofile(path_local_video, codec='libx264',
                          audio_bitrate=target_bitrate, fps=video.fps, audio_codec='aac')
    video.close()
    path_video = upload_file(path_local_video, ".mp4")
    paths = [path_audio, path_video]
    return ",".join(paths)


def fenli(url, type="mp4"):
    start_time = time.time()
    local_name = download_video(url, 'tmp1', type)
    if local_name is None:
        v_logger.info(f"下载视频报错")
        return None
    if type == "mp4":
        content = compress_video(local_name)

    end_time = time.time()

    execution_time = end_time - start_time  # 计算执行时间
    v_logger.info(f"函数执行时间为: {execution_time} 秒")
    return content


if __name__ == '__main__':
    # text = main("https://v26-cold.douyinvod.com/9e50237f7ce5421afb0e44a44be47046/66a74db8/video/tos/cn/tos-cn-ve-15/oorNCbTBEegFyuXADAGIN5Lp7mILDBQeBfcEta/?a=1128&ch=0&cr=0&dr=0&cd=0%7C0%7C0%7C0&cv=1&br=1268&bt=1268&cs=0&ds=3&ft=BaXAWVVywfURsm80mo~pK7pswApIB8FwvrK4YVn2do0g3cI&mime_type=video_mp4&qs=0&rc=ODo1ZDo7aWc2OTQ8ZThmZ0BpamdpbHg5cnFvdDMzNGkzM0AwNDM1MGItX2IxNmEtNDA2YSNwMi4yMmRrbWFgLS1kLWFzcw%3D%3D&btag=c0010e00088000&cquery=100y&dy_q=1722236830&feature_id=f0150a16a324336cda5d6dd0b69ed299&l=20240729150710A1ABAAE6223D450041EE")
    # # # 创建ArgumentParser对象
    # # parser = argparse.ArgumentParser(description='Process some inputs.')
    # # # 添加参数
    # # parser.add_argument('-url', type=str, required=True,
    # #                     help='The id of the url')
    # # # 解析参数
    # # args = parser.parse_args()
    # # # 使用参数
    # text = main("https://v9-web.toutiaovod.com/9eab6e8c5657a303e112a289cff37214/66af39d3/video/tos/cn/tos-cn-o-0004/509b238c3815445b9b1227ebae3d209a/media-audio-und-mp4a/?a=24&ch=0&cr=0&dr=0&er=0&lr=unwatermarked&net=5&cd=0%7C0%7C0%7C0&cv=1&br=64&bt=64&cs=0&mime_type=video_mp4&qs=0&rc=OWg2OjllZmU8N2g8NTZnNEBpM2U6Zmo5cnV5czMzNDczM0BfMjAxMDFhMS4vNTVhMF4vYSNsbGZnMmRraW1gLS1kLS9zcw%3D%3D&btag=c0000e00030000&dy_q=1722755731&l=202408041515319442B17AB3F060042615", "mp3")

    # # text = main("https://v3-cold.douyinvod.com/f1ca8ccdfb92efc76b65e7b08ae3ea38/66af3f8b/video/tos/cn/tos-cn-ve-15/oEdmkWSmTAz1R9IogIiRlzDBaf1PZVeiAAByXE/?a=1128&ch=0&cr=0&dr=0&cd=0%7C0%7C0%7C0&cv=1&br=1354&bt=1354&cs=0&ds=3&ft=H4NIhvvBQOBULry78Z.6TQjSYZhPkjDtGi-6UTRq8_45a&mime_type=video_mp4&qs=0&rc=Ozg8NTU0ODU4Zjw7ZmZlaUBpamlzd285cmd2dDMzNGkzM0AtMTYyY14yNTUxNmIxYV8yYSM1ZmBiMmRjZl9gLS1kLTBzcw%3D%3D&btag=80010e000b0001&cquery=100y&dy_q=1722756993&feature_id=f0150a16a324336cda5d6dd0b69ed299&l=202408041536334061FE02E8CC542629A8")

    print(f"<start><end>")
    audio_file_name = video2audio("input/1.mp4", "tmp")
